package com.guigu.dispatch.utils;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.net.HttpCookie;
import java.util.*;

/**
 * @ClassName:OkHttpUtils
 * @Description://TODO
 * @Author:taoLong
 * @Date:2021/11/19:14:52 星期五
 * @email:2391611102@qq.com or 2391611102qq@gmail.com
 */
public class OkHttpUtils {


    /**
     * 获取xxl-job登录信息中的cookie
     *
     * @return
     */
    public static String getCookie() {
        Map<String, Object> map = new HashMap<>();
        map.put("userName", "admin");
        map.put("password", "123456");

        HttpResponse response = HttpRequest.post(XxlJobHttpURL.XXL_LOGIN).form(map).execute();

        List<HttpCookie> cookies = response.getCookies();

        StringBuilder str = new StringBuilder();

        for (HttpCookie cookie : cookies) {
            str.append(cookie.toString());
        }

        String cookie = str.toString();
        /**
         * 返回获取到的cookie
         */
        return cookie;
    }


    /**
     * 获取当前任务日记
     *
     * @return
     */
    public static LinkedHashMap<String, Object> getXxlLogInfo() {
        try {
            Map<String,Object> fromMap=new HashMap<>();
            fromMap.put("jobGroup","0");
            fromMap.put("jobId","0");
            fromMap.put("logStatus","-1");
            HttpResponse httpResponse = HttpRequest.post(XxlJobHttpURL.XXL_LOG_INFO).cookie(getCookie()).form(fromMap).execute();
            String body = httpResponse.body();
            ObjectMapper objectMapper = new ObjectMapper();
            Map<String, Object> map = objectMapper.readValue(body, Map.class);
            ArrayList<LinkedHashMap<String, Object>> jobLogList= (ArrayList<LinkedHashMap<String, Object>>) map.get("data");
            return jobLogList.get(0);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return null;

    }
}
